package com;

import com.utils.GlassPrinter;
import com.utils.JettyServletRunner;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class TetrisServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String figure = req.getParameter("figure");
        int x = Integer.parseInt(req.getParameter("x"));
        int y = Integer.parseInt(req.getParameter("y"));
        String glass = req.getParameter("glass");
        String answer = answer(figure, x, y, glass);
        System.out.println("-------\n" + GlassPrinter.toString(answer, figure, x, y, glass));
        System.out.println("Answer: " + answer);
        resp.getWriter().write(answer);
    }

    public static void main(String[] args) throws Exception {
        new JettyServletRunner().run();
    }

    public static final int GLASS_HEIGHT = 20;
    public static final int GLASS_WIDTH = 10;

    public static final int NO_ROTATE = 0;
    public static final int ROTATE_90 = 1;
    public static final int ROTATE_180 = 2;
    public static final int ROTATE_270 = 3;
    
    private int figureCounter = 0;

    public String answer(String figure, int x, int y, String stringGlass) {
    	figureCounter++;
    	
    	if (figure.equals("O")) {
    		return handleO();
    	} else {
    		return handleI();
    	}
    }
    
    private String handleO() {
    	
    	switch (figureCounter%5) {
    	case 1:
    		return "left=4, drop";
    		
    	case 2:
    		return "left=2, drop";
    		
    	case 3:
    		return "drop";
    		
    	case 4:
    		return "right=2, drop";
    		
    	default:
    		return "right=4, drop";
    	}	
    }
    
    private String handleI() {
    	if (figureCounter%10 == 0) {
    		return "right=5, drop";
    	}
    	
    	if (figureCounter%9 == 0) {
    		return "right=4, drop";
    	}
    	
    	if (figureCounter%2 == 0) {
    		return "rotate=1, right=2, drop";
    	}
    	
        return "rotate=1, left=2, drop";
    }
    
}
